//CHUCK TODO Change the name of this jsp!!
//Should we write some kind of acknowlegment that the new pet was added?

var delimiter = '_'
var prefix = 'petAndVisitDiv' + delimiter
var index = parseInt(${index}) 
var afterThisDivId = index - 1 < 0 ? 'afterMe' : prefix + (index - 1)
var thisDivId = prefix + index

//Need to shift ids of all the divs with index >= our index

$('div[id^=petAndVisitDiv_]')
//shiftIds( $('div[id^=' + prefix + '}'), delimiter, index   )
//CHUCK TODO Use variables, like above (except that above doesn't work)
shiftIds( $('div[id^=petAndVisitDiv]'), delimiter, index   )
shiftIds( $('form[id^=editPetForm]'), delimiter, index   )
shiftIds( $('form[id^=addVisitForm]'), delimiter, index   )

var toInsert = "<div id='"+thisDivId+"' class='replaceMe'>" + window.data[thisDivId] + "</div>"

$(toInsert).insertAfter($('#'+afterThisDivId))

//Make new forms remotable
//CHUCK TODO  This should probably be done by liveQuery plugin. See 'jQuery In Action' book
var editForm = 'editPetForm_'
var visitForm = 'addVisitForm_'

var editFormSelector = 'form[id^='+editForm+']'
var visitFormSelector = 'form[id^='+visitForm+']'
$(editFormSelector).each(function() {
	$.remoteForm(this.id)
})
$(visitFormSelector).each(function() {
	$.remoteForm(this.id)
})

//Chuck TODO This should be on jsonHelp js file and should be the kind of jQuery function
//that returns a wrappedSet, rather than being a regular utility function.
//See jQuery in Action book.  This function should probably then be invoked in a different
//way
function shiftIds(wrappedSet, delimiter, startHere){
   
   wrappedSet.each(function(){
       var arr = this.id.split(delimiter)
       var prefix = arr[0] + delimiter
       var i = parseInt(arr[1])
       if(i >= startHere){
          this.id = prefix + (i + 1)
       }
   })
   
   return wrappedSet
   

}

